package server

import (
	"gitee.com/llakcs/agile-go/log"
	"gitee.com/llakcs/agile-go/transport"
	"gitee.com/llakcs/agile-go/transport/http"
	"gitee.com/llakcs/aglie-layout/api"
	"gitee.com/llakcs/aglie-layout/conf"
	"github.com/gin-gonic/gin"
	"time"
)

func NewHttpServer(conf *conf.HttpConf) transport.Server {
	gin.SetMode(gin.ReleaseMode) //默认的日志级别
	r := gin.Default()
	r.Use(logMiddleware())
	r.GET("/testGet", api.HandlerDemo)
	var opts = []http.ServerOption{
		http.WithRouter(r),
		http.WithServerAddress(conf.Addr),
	}
	return http.NewServer(opts...)
}

func logMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		//开始时间
		startTime := time.Now()
		//处理请求
		c.Next()
		//结束时间
		endTime := time.Now()
		// 执行时间
		latencyTime := endTime.Sub(startTime)
		//请求方式
		reqMethod := c.Request.Method
		//请求路由
		reqUrl := c.Request.RequestURI
		//状态码
		statusCode := c.Writer.Status()
		//请求ip
		clientIP := c.ClientIP()
		log.Infow("status_code：", statusCode, "latency_time:", latencyTime, "client_ip:", clientIP, "req_method:", reqMethod, "req_uri:", reqUrl)
	}
}
